package shop.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import shop.dao.UserDao;
import shop.entity.User;
import shop.util.DBUtil;

public class UserDaoImpl implements UserDao {

	@Override
	public void add(User user) {
		String sql = "INSERT INTO `interesting_shop_db`.`t_user`( `account`, `nick_name`, `password`, `gender`, `id_card_no`, `email`, `phone`, `type`, `open_id`) VALUES (?,?,?,?,?,?,?,?,?)";
		Object[] params = new Object[] {user.getAccount(),user.getNickName(),user.getPassword(),user.getGender(),user.getIdCardNo(),user.getEmail(),user.getPhone(),user.getType(),user.getOpenId()};
		DBUtil.update(sql, params);
	}

	@Override
	public User login(String account, String password) {
		User user = null;
		String sql = "select * from t_user where account=? and password=?";
		Object[] params = new Object[] {account,password};
		ResultSet rs = DBUtil.query(sql, params);
		try {
			if(rs.next()) {
				int id = rs.getInt("id");
				String account1 = rs.getString("account");
				String nickName = rs.getString("nick_name");
				String password1 = rs.getString("password");
				int gender = rs.getInt("gender");
				String idCardNo = rs.getString("id_card_no");
				String email = rs.getString("email");
				String phone = rs.getString("phone");
				int type = rs.getInt("type");
				String openId = rs.getString("open_id");
				String face = rs.getString("face");
				String level = rs.getString("level");
				Date loginTime = rs.getDate("login_time");
				Date registTime = rs.getDate("regist_time");
				double consume = rs.getDouble("consume");
				double balance = rs.getDouble("balance");
				user = new User(id, account1, nickName, password1, gender, idCardNo, email, phone, type, openId, face, loginTime, level, consume, balance, registTime);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public void changeFace(int uid,String name) {
		String sql = "update t_user set face = ? where id = ?";
		Object[] params = new Object[] {name,uid};
		DBUtil.update(sql, params);
		
	}

	@Override
	public void editNickName(String nickName, int id) {
		String sql = "update t_user set nick_name = ? where id = ?";
		Object[] params = new Object[] {nickName,id};
		DBUtil.update(sql, params);
		
	}

	@Override
	public void editPhone(String newPhone,int id) {
		String sql = "update t_user set phone = ? where id = ?";
		Object[] params = new Object[] {newPhone,id};
		DBUtil.update(sql, params);
		
	}

	@Override
	public void editEmail(String newEmail, int id) {
		String sql = "update t_user set email = ? where id = ?";
		Object[] params = new Object[] {newEmail,id};
		DBUtil.update(sql, params);
		
	}

	@Override
	public void editPassword(String newPassword, int id) {
		String sql = "update t_user set password = ? where id = ?";
		Object[] params = new Object[] {newPassword,id};
		DBUtil.update(sql, params);
		
	}


}
